package practice1;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import util.Schema;

public class MessageDAO {

	public static void main(String[] args) {

		// ########## unit 1 ：插入 ##############
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		Message message = new Message("错的不是我，是世界！@C.C");
		System.out.println(" >>> Unit1：执行持久化  <<<");
		session.save(message);
		System.out.println("\n");
		tx.commit();
		session.  close();

		// ################### unit 2：查询 #############
		Session secondSession = HibernateUtil.getSessionFactory().openSession();
		System.out.println(" >>> Unit2：全表查询  <<<");
		Query q = secondSession.createQuery("from Message m order by m.text asc");
		List messages = q.list();
		System.out.println("目前共有:["+messages.size()+"]条消息，内容如下：");

		for (Iterator iter = messages.iterator(); iter.hasNext();) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
			//System.out.println(loadedMsg.getCount());
		}

		System.out.println("\n");
		secondSession.close();

		// ############### unit 3：修改　 ##########################
		Session thirdSession = HibernateUtil.getSessionFactory().openSession();
		Transaction thirdTransaction = thirdSession.beginTransaction();

		// message.getId() holds the identifier value of the first message
		System.out.println(">>> Unit3： 读取并改写Unit1的记录内容  <<<");
		Message loadedMessage = (Message) thirdSession.get(Message.class, message.getId());
		System.out.println(" >>> 修改...");
		loadedMessage.setText("中二是一种病。。。。");
		loadedMessage.setOriMessage(new Message("知道雪为什么是白色的么？因为它忘记了本来的颜色！"));//自动insert
		System.out.println("\n");
		thirdTransaction.commit();//自动脏检查：未直接出现保存语句
		thirdSession.close();
		// #################### Unit4 ：查询以验证修改生效 ######################
		Session fourthSession = HibernateUtil.getSessionFactory().openSession();
		System.out.println(" >>> Final Unit：全表查询  <<< ");
		messages = fourthSession.createQuery("from Message m order by m.text asc").list();
		System.out.println("目前共有:["+messages.size()+"]条消息，内容如下：");
		for (Iterator iter = messages.iterator(); iter.hasNext();) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
		}
		fourthSession.close();

		// Shutting down the application
		HibernateUtil.shutdown();

		// #################### 查看schema ######################
		System.out.println("\n >>> 查看 schema:  <<< ");
		Schema.getSchema();
	}
}
